//
//  SearchView.swift
//  Employee
//
//  Created by tancheng on 2018/7/23.
//  Copyright © 2018年 remotevillage. All rights reserved.
//

import Foundation
import RxSwift

class SearchView: UIView {
    
    var bgView: UIView!
    var textField: UITextField!
    
    var topPadding: CGFloat = 13
    var leftPadding: CGFloat = 10
    
    weak var delegate: SearchViewDelegate?
    
    fileprivate let disposeBag = DisposeBag()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        backgroundColor = .white
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        
        bgView = UIView(frame: CGRectMake(leftPadding, topPadding, bounds.width-2*leftPadding, bounds.height - 2*topPadding))
        bgView.backgroundColor = UIColor.hex("#f5f5f5")
        bgView.layer.cornerRadius = 2
        bgView.layer.masksToBounds = true
        addSubview(bgView)
        
        let searchIconFrame = CGRect(x: 0, y: 0, width: 30, height: 14)
        let searchIconImageView = UIImageView(frame: searchIconFrame)
        let searchIconImage = UIImage(named: "SearchContactsBarIcon")
        searchIconImageView.image = searchIconImage
        searchIconImageView.contentMode = .scaleAspectFit
        
        let rightButtonFrame = CGRect(x: UIScreen.width - 38, y: 8, width: 28, height: 28)
        let rightButton = UIButton(frame: rightButtonFrame)
        let rightButtonimage = UIImage(named: "card_delete")
        rightButton.setImage(rightButtonimage, for: .normal)
        rightButton.rx.tap.subscribe(onNext: {[weak self] (_) in
            self?.textField.text = ""
            self?.delegate?.searchTextChange(text: "")
        }).disposed(by: disposeBag)
    
        textField = UITextField()
        textField.frame = CGRectMake(0, 0, bgView.bounds.width, bgView.bounds.height)
        textField.leftView = searchIconImageView
        textField.leftViewMode = .always
        textField.rightView = rightButton
        textField.rightViewMode = .whileEditing
        textField.font = UIFont.systemFont(ofSize: 16)
        textField.rx.text.orEmpty.subscribe(onNext: {[weak self] (text) in
            print(text)
            self?.delegate?.searchTextChange(text: text)
        }).disposed(by: disposeBag)
        textField.placeholder = "房号/客户姓名"
        bgView.addSubview(textField)
        
       
        
        
    }
    
}

protocol SearchViewDelegate: class {
    func searchTextChange(text: String)
}

extension SearchView: UITextFieldDelegate {
    
}
